<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>

    <!-- 清楚默认样式 -->
    <link rel="stylesheet" href="./../static/CSS/base.css">
    <link rel="stylesheet" href="./../static/CSS/login.css">
</head>

<body>
<div class="login-container">
    <h2>电子产品售后服务网站登录</h2>
    <form id="login-form" action="/login" method="POST">
        <input type="hidden" name="next" value="">
        <div class="input-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" placeholder="请输入用户名" required>
        </div>
        <div class="input-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
        </div>
        <button type="submit" onclick="checkCredentials()">登录</button>
    </form>
    <p>
    还没有账号？<a href="/register">立即注册</a>
    </p>
</div>

<script>
    async function checkCredentials(event) {
        event.preventDefault(); // 阻止表单默认提交

    const form = document.getElementById('login-form');
    const formData = new FormData(form);
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');

    try {
        const response = await fetch('/login', {
        method: 'POST',
        body: formData,
        });
        if (response.redirected) {
          // 登录成功，跳转
        window.location.href = response.url;
        } else {
        const errorText = await response.text();

        if (errorText.includes("密码错误")) {
            // 密码错误：仅清空密码栏
            passwordInput.value = "";
            alert("密码错误，请重新输入！");
        } else if (errorText.includes("用户不存在")) {
            // 用户不存在：清空所有输入
            usernameInput.value = "";
            passwordInput.value = "";
            alert("用户不存在，请检查用户名！");
        } else {
            // 其他错误
            alert(errorText);
        }
        }
    } catch (error) {
        alert("网络错误，请重试");
    }
    }
    // 绑定表单提交事件
    document.getElementById('login-form').addEventListener('submit', checkCredentials);
</script>
</body>

</html>